<?php
/**
 * Created by PhpStorm.
 * User: cephei
 * Date: 12/19/15
 * Time: 4:25 PM
 */

namespace Plugins\Installer;


use Core\PluginContainer;

class Plugin_Installer
{
    private $dependceRepo = "";
    private $modules=[];

    public function __construct()
    {
        $json = file_get_contents(ROOT_PATH . '/Configs/Modules.json');
        $this->modules = json_decode($json, true);
    }

    public function installPlugin($filePath, $force)
    {
        $zipFile = zip_open($filePath);
        if ($zipFile) {
            $nameSpace = '';
            $fileList = [];
            while ($zipEntry = zip_read($zipFile)) {
                $fileName = zip_entry_name($zipEntry);
                $fileList[$fileName] = '';
                $installScript = '';
                if (strpos($fileName, ".install") !== false) {
                    while ($data = zip_entry_read($zipEntry)) {
                        $installScript .= $data;
                    }
                } else {
                    while ($data = zip_entry_read($zipEntry)) {
                        $fileList[$fileName] .= $data;
                    }
                }
                if ($installScript != "") {
                    $installObject = json_decode($installScript, true);
                    $config = [];
                    $config["id"] = $installObject["id"];
                    $config["class"] = $installScript["namespace"];
                    $config["version"] = $installObject["version"];
                    $config["enable"] = 1;
                    if(isset($installObject["dependence"])){
                        foreach ($installObject["dependence"] as $dependence) {
                            $dependenceFile = $this->solveDependence($dependence["id"],$dependence["required"]);
                            if($dependenceFile!==false){
                                $this->installPlugin($dependenceFile);
                            }
                        }
                    }
                }

//                    $file = fopen($this->createPath($fileName), 'a');
//
//                    fclose($file);
//                    if (preg_match('/Register_.*?/', $fileName)) {
//                        $nameSpace = $fileName;
//                    }
            }
        }
        if ($nameSpace != '') {
            $nameSpace = str_replace('/', '\\', $nameSpace);
            $nameSpace = str_replace('.php', '', $nameSpace);
            $instance = new $nameSpace();
            if (method_exists($instance, 'install')) {
                $instance->install(function ($config) {
                    $this->addToModule($config);
                });
            }
        }
    }

    private function createPath($fileName)
    {
        $pathList = explode('/', $fileName);
        $path = ROOT_PATH;
        for ($i = 0; $i < count($pathList) - 1; $i++) {
            $path = $path . '/' . $pathList[$i];
            if (!is_dir($path)) ;
            mkdir($path);
        }
        return ROOT_PATH . '/' . $fileName;
    }

    public function addToModule($config)
    {
        $json = file_get_contents(ROOT_PATH . '/Configs/Modules.json');
        $obj = json_decode($json, true);
        $obj[$config["id"]] = [
            "class" => $config["class"],
            "version" => $config["version"],
            "enable" => $config["enable"]
        ];
        $json = json_encode($obj);
        file_put_contents(ROOT_PATH . '/Configs/Modules.json', $json);

    }

    public function solveDependence($id,$version){
        if(array_key_exists("curl",$this->modules)) {
            $http = PluginContainer::getInstance()->make("curl");
            $response = $http->sendRequest("{$this->dependceRepo}/$id/$version.zip");
            $fileName = ROOT_PATH . md5(time()) . ".zip";
            file_put_contents($fileName, $response);
            return $fileName;
        }
        return false;

    }
}